// $URL: http://mingw-lib.googlecode.com/svn/trunk/local/box/yt_dump_lib/t_youtube_dump_lib.cpp $
// $Rev: 800 $
// $Author: akio.miyoshi $
// $Date:: 2013-01-01 12:38:21 +0000#$

#include "t_youtube_dump_lib.h"
#include <QtGui>

T_Youtube_Dump_Lib::T_Youtube_Dump_Lib()
{
}

QSqlDatabase T_Youtube_Dump_Lib::getDumpDatabase()
{
#if 0x1
    ////QString v_db_path = "E:/Qt/yt_dump.mdb";
    QString v_db_path = "C:/yt_dump.mdb";
    QSqlDatabase m_db = QSqlDatabase::addDatabase("QODBC");
    m_db.setDatabaseName(
            QString("DRIVER={Microsoft Access Driver (*.mdb)};FIL={MS Access};DBQ=%1;")
            .arg(v_db_path)
            );
#else
    QString v_db_path = "E:/Qt/yt_dump.sqlite";
    QSqlDatabase m_db = QSqlDatabase::addDatabase("QSQLITE");
    m_db.setDatabaseName(v_db_path);
#endif
    return m_db;
}

void T_Youtube_Dump_Lib::getDownloadExe(QFile &a_file)
{
    //a_file.setFileName("E:/qt/mingw-lib/yt_download_top-build-desktop-Qt_4_8_1_for_Desktop_-_MinGW__Qt_SDK__Release/box/yt_download/release/yt_download.exe");
    //a_file.setFileName("C:/usr/local/debug/yt_download.exe");
    a_file.setFileName("C:/usr/local/release/yt_download.exe");
}

QString T_Youtube_Dump_Lib::getVideoStreamMap(
        QNetworkAccessManager *a_nam, QString a_id, QMap<int, QUrl> &a_fmt_map, QStringList &a_error_list)
{
    QStringList v_parts;
    //v_parts << "&el=embedded" << "&el=detailpage" << "&el=vevo" << "";
    v_parts << "&el=detailpage";
    QString v_part;
    QString v_token = "";
    foreach(v_part, v_parts)
    {
        //[Get Token]
        QString v_url_1 =
                QString("http://www.youtube.com/get_video_info?&video_id=%1%2&ps=default&eurl=&gl=US&hl=en")
                .arg(a_id).arg(v_part);
        QByteArray v_params_1 = batchGet(a_nam, v_url_1);
        v_params_1.prepend("?");
        QString v_dirPath = QDesktopServices::storageLocation(QDesktopServices::DesktopLocation);
        QDir v_dir(v_dirPath);
        QString v_filePath = v_dir.filePath("getTokenForVideoStreamEmbed.txt");
        qDebug() << "[getTokenForVideoStreamEmbed()]" << v_filePath;
        QFile v_file(v_filePath);
        v_file.open(QIODevice::WriteOnly);
        v_file.write(v_params_1);
        v_file.close();

        QUrl v_params_2;
        v_params_2.setEncodedUrl(v_params_1);
        QString v_status = v_params_2.queryItemValue("status");
        QString v_reason = v_params_2.queryItemValue("reason");
        v_token = v_params_2.encodedQueryItemValue("token");
        QString v_fmt_stream_map = v_params_2.queryItemValue("url_encoded_fmt_stream_map");
        qDebug() << "[v_status(getTokenForVideoStreamEmbed)]" << v_status << v_reason; //<< v_fmt_stream_map;
        a_fmt_map.clear();
        if(v_status == "fail")
        {
            a_error_list.append(v_reason);
            continue;
        }
        if(v_fmt_stream_map != "")
        {
            QStringList v_slist_1 = v_fmt_stream_map.split(',');
            for(int i=0; i<v_slist_1.size(); i++)
            {
                QByteArray v_params_1 = v_slist_1.at(i).toLatin1();
                v_params_1.prepend("?");
                QUrl v_params_2;
                v_params_2.setEncodedUrl(v_params_1);
                QString v_stream_url = v_params_2.queryItemValue("url");
                if(!v_params_2.hasQueryItem("url"))
                {
                    v_stream_url = v_params_2.queryItemValue("conn") + QString("/?stream=") + v_params_2.encodedQueryItemValue("stream");
                }
                else
                {
                    QString v_sig = v_params_2.queryItemValue("sig");
                    qDebug() << "[v_sig]" << v_sig;
                    v_stream_url += "&signature=" + v_sig;
                }
                int v_fmt = v_params_2.queryItemValue("itag").toInt();

                if(v_stream_url.isEmpty())
                {
                    a_error_list.append(QString("埋め込みFLASHからStream URLが見つかりません(1): %1")
                                        .arg(v_params_2.queryItemValue("conn")));
                }
                a_fmt_map.insert(v_fmt, v_stream_url);
            }
        }
        qDebug() << "[v_token]" << v_token << v_part;
        break;
    }
    return v_token;
}

QString T_Youtube_Dump_Lib::getVideoInfo(
        QNetworkAccessManager *a_nam, QString a_id, T_Youtube_Video_Info *a_video_info)
{
    QString v_token = "";
    //[Get Token]
    QString v_url_1 =
            QString("http://www.youtube.com/get_video_info?&video_id=%1&el=detailpage&ps=default&eurl=&gl=US&hl=en")
            .arg(a_id);
    QByteArray v_params_1 = batchGet(a_nam, v_url_1);
    v_params_1.prepend("?");
    QString v_dirPath = QDesktopServices::storageLocation(QDesktopServices::DesktopLocation);
    QDir v_dir(v_dirPath);
    QString v_filePath = v_dir.filePath("getTokenForVideoStreamEmbed.txt");
    qDebug() << "[getTokenForVideoStreamEmbed()]" << v_filePath;
    QFile v_file(v_filePath);
    v_file.open(QIODevice::WriteOnly);
    v_file.write(v_params_1);
    v_file.close();

    QUrl v_params_2;
    v_params_2.setEncodedUrl(v_params_1);
    //[status][token]
    QString v_status = v_params_2.queryItemValue("status");
    QString v_reason = v_params_2.queryItemValue("reason");
    //[title]
    QByteArray v_title_array = v_params_2.encodedQueryItemValue("title");
    v_title_array.replace("+", " ");
    a_video_info->f_title = QUrl::fromPercentEncoding(v_title_array);
    //[token]
    v_token = v_params_2.encodedQueryItemValue("token");
    //[status == fail]
    if(v_status == "fail")
    {
        a_video_info->f_error_list.append(v_reason);
        return "";
    }
    //[v_fmt_size_map]
    QString v_fmt_list = v_params_2.queryItemValue("fmt_list");
    qDebug() << "[v_fmt_list]" << v_fmt_list;
    ////QMap<int, QString> f_fmt_size_map;
    a_video_info->f_fmt_size_map.clear();
    QStringList v_fmt_size_split = v_fmt_list.split(",");
    for(int i=0; i<v_fmt_size_split.size(); i++)
    {
        QStringList v_split = v_fmt_size_split.at(i).split("/");
        a_video_info->f_fmt_size_map.insert(v_split.at(0).toInt(), v_split.at(1));
    }
    qDebug() << "[v_fmt_size_map]" << a_video_info->f_fmt_size_map;
    //[url_encoded_fmt_stream_map]
    QString v_fmt_stream_map = v_params_2.queryItemValue("url_encoded_fmt_stream_map");
    qDebug() << "[v_status(getTokenForVideoStreamEmbed)]" << v_status << v_reason;
    a_video_info->f_fmt_map.clear();
    if(v_fmt_stream_map != "")
    {
        QStringList v_slist_1 = v_fmt_stream_map.split(',');
        for(int i=0; i<v_slist_1.size(); i++)
        {
            QByteArray v_params_1 = v_slist_1.at(i).toLatin1();
            v_params_1.prepend("?");
            QUrl v_params_2;
            v_params_2.setEncodedUrl(v_params_1);
            QString v_stream_url = v_params_2.queryItemValue("url");
            if(!v_params_2.hasQueryItem("url"))
            {
                v_stream_url = v_params_2.queryItemValue("conn") + QString("/?stream=") + v_params_2.encodedQueryItemValue("stream");
            }
            else
            {
                QString v_sig = v_params_2.queryItemValue("sig");
                qDebug() << "[v_sig]" << v_sig;
                v_stream_url += "&signature=" + v_sig;
            }
            int v_fmt = v_params_2.queryItemValue("itag").toInt();

            if(v_stream_url.isEmpty())
            {
                a_video_info->f_error_list.append(QString("埋め込みFLASHからStream URLが見つかりません(1): %1")
                                                  .arg(v_params_2.queryItemValue("conn")));
            }
            a_video_info->f_fmt_map.insert(v_fmt, v_stream_url);
        }
    }
    qDebug() << "[v_token]" << v_token;
    return v_token;
}

QString T_Youtube_Dump_Lib::getFFMpegExe()
{
    QString v_app_dir_path = QCoreApplication::applicationDirPath();
    qDebug() << "[T_Youtube_Dump_Lib::getFFMpegExe(1a)]" << v_app_dir_path;
    QString v_dl_exe_path = v_app_dir_path + "/../../tools/ffmpeg/bin/ffmpeg.exe";
    qDebug() << "[T_Youtube_Dump_Lib::getFFMpegExe(2e)]" << v_dl_exe_path;
    if(QFileInfo(v_dl_exe_path).exists())
    {
        QString v_cann_file_path = QFileInfo(v_dl_exe_path).canonicalFilePath();
        v_cann_file_path = QDir::toNativeSeparators(v_cann_file_path);
        return v_cann_file_path;
    }
    return "ffmpeg.exe";
}

QString T_Youtube_Dump_Lib::getToolsExe(const QString &a_exe_name, bool a_quote)
{
    QString v_app_dir_path = QCoreApplication::applicationDirPath();
    qDebug() << "[T_Youtube_Dump_Lib::getToolsExe(1a)]" << v_app_dir_path;
    QString v_dl_exe_path = v_app_dir_path + "/../../tools/"+ a_exe_name + "/bin/" + a_exe_name + ".exe";
    qDebug() << "[T_Youtube_Dump_Lib::getToolsExe(2e)]" << v_dl_exe_path;
    if(QFileInfo(v_dl_exe_path).exists())
    {
        QString v_cann_file_path = QFileInfo(v_dl_exe_path).canonicalFilePath();
        v_cann_file_path = QDir::toNativeSeparators(v_cann_file_path);
        if(a_quote)
        {
            v_cann_file_path = QString("\"") + v_cann_file_path + QString("\"");
        }
        return v_cann_file_path;
    }
    if(a_quote)
    {
        return QString("\"") + a_exe_name + QString("\"");
    }
    return a_exe_name;
}
